#include "DiscoverService.h"
#include "../include/proto.h"
#include "GlobalSetting.h"
int DiscoverService::open(ACE_Reactor *react){
	this->reactor(react);
	if (-1==sd_server_.open(ACE_INET_Addr(DISCOVERSERVICE_SERVER_PORT))){
		ACE_DEBUG((LM_DEBUG,"CameraData_Handle open sock %p(%d)\n","failed", ACE_OS::last_error()));
		return -1;
	}
	int flag=1;
	int rt=sd_server_.set_option(SOL_SOCKET,SO_BROADCAST,&flag,sizeof(flag));
	rt= this->reactor()->register_handler(this, ACE_Event_Handler::READ_MASK);
	return rt;
}

int DiscoverService::handle_input (ACE_HANDLE fd = ACE_INVALID_HANDLE){
	ACE_UNUSED_ARG(fd);
	CommandHead data;
	ACE_INET_Addr client_addr;
	int rt=sd_server_.recv(&data,sizeof(data),client_addr);
	if (rt<=0) return 0;
	CommandHead *reply=(CommandHead *)GlobalSetting_Single::instance()->CommandProcess(&data);
	if (reply!=NULL){
		ACE_INET_Addr dst("255.255.255.255:123");
		rt=sd_server_.send(reply,htons(reply->wCommandLen),dst);
		ACE_DEBUG((LM_DEBUG,"%p reply->wCommandLen=%d rt=%d \n","error",htons(reply->wCommandLen),rt));
	}
	return 0;
}

int DiscoverService::handle_close(ACE_HANDLE handle, ACE_Reactor_Mask close_mask){
	sd_server_.close();
	return 0;
}

int DiscoverService::close(){
	reactor()->remove_handler(this,READ_MASK|DONT_CALL);
	sd_server_.close();
	return 0;
}
